<?php

/**
 * 事件管理
 *
 * 事件监听、触发
 *
 * @author Lan <lanyg.com@gmail.com>
 * @link http://www.lanyg.com/projects/lanp
 * @copyright Copyright &copy; 2011-2012 Yanguang Lan (www.lanyg.com)
 * @license LGPL (http://www.gnu.org/licenses/lgpl.html)
 * @version $Id$
 */

/**
 * MVC_Event
 *
 * @package lanp
 * @author Lan
 */

class MVC_Event
{
    /*
     * @the handlers array
     * @access private
     */
    private $handlers = array();

    /**
     * 构造函数
     *
     * @access public
     */

    public function  __construct()
    {
        MVC::instance($this, 'event');
    }

    /**
     * 监听事件
     *
     * @param string $e
     * @param object $handler
     */
    public function addEventListener($e, $handler) {
            empty($this->handlers[$e]) && $this->handlers[$e] = array();
            array_push($this->handlers[$e], $handler);
    }

    /**
     * 触发事件
     *
     * @param string $e
     * @param string $param
     * @return bool
     */
    public function callEventHandler($e, $param = array()) {
            if(empty($this->handlers[$e])) {
                    return false;
            }

            if(empty($param) && func_num_args() > 1) {
                    $param = array_slice(func_get_args(), 1);
            }

            foreach($this->handlers[$e] as $fun) {
                    if(is_string($fun) && function_exists($fun)) {
                            call_user_func_array($fun, $param);
                    } else
                            if(is_array($fun)) {
                                    list($class, $method) = $fun;
                                    if(method_exists($class, $method)) {
                                            call_user_func_array(array($class, $method), $param);
                                    }
                            } else {
                                    //call func no exist
                            }
            }
    }
}
?>